﻿using AspNetCoreRateLimit;
using Developer.Core.FrameWork.GlobalVar;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Developer.Core.FrameWork.IPLimit
{
    /// <summary>
    /// IP限流扩展类
    /// </summary>
    public static class IPLimitServiceCollectionExtensions
    {
        public static void AddIPLimit(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            // 是否开启IP限流
            if (GlobalVars.IsIPLimit)
            {
                services.AddMemoryCache();

                services.Configure<IpRateLimitOptions>(configuration.GetSection("IpRateLimiting"));

                services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();

                services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

                services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

                services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
            }
        }
    }
}
